package com.example.ftpserver;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {
    private final String TAG = "MainActivity";
    private final int REQUEST_PERMISSION_LOCATION = 1;

    private TextView textView;

    private final String[] permissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
//            Manifest.permission.INTERNET,
//            Manifest.permission.ACCESS_NETWORK_STATE,
//            Manifest.permission.ACCESS_WIFI_STATE,
//            Manifest.permission.ACCESS_FINE_LOCATION,
//            Manifest.permission.ACCESS_COARSE_LOCATION,
////            Manifest.permission.ACCESS_BACKGROUND_LOCATION,
//            Manifest.permission.WAKE_LOCK,
//            Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
//            Manifest.permission.READ_PHONE_STATE,
//            Manifest.permission.FOREGROUND_SERVICE,
//            Manifest.permission.RECEIVE_BOOT_COMPLETED,
//            Manifest.permission.CAMERA,
////            Manifest.permission.REQUEST_INSTALL_PACKAGES,
//            Manifest.permission.RESTART_PACKAGES,
//            Manifest.permission.GET_TASKS,
//            Manifest.permission.CHANGE_NETWORK_STATE,
//            Manifest.permission.CHANGE_WIFI_STATE,
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.textView);

        initPermission();
    }

    private void initPermission() {
        List<String> permissionList = new ArrayList<>();

        for (String permission : permissions) {

            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission);
            }
        }

        if (!permissionList.isEmpty()) {
            ActivityCompat.requestPermissions(this, permissionList.toArray(new String[permissionList.size()]), 1);
        } else {
            init();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull @NotNull String[] permissions, @NonNull @NotNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        int locationFlags = 0;
        if (requestCode == REQUEST_PERMISSION_LOCATION) {

            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    locationFlags += 1;
                }
            }

            if (locationFlags != permissions.length) {
                Toast.makeText(this, "请允许所有权限！", Toast.LENGTH_LONG).show();
                // 结束程序
            } else {
                init();
            }
        }
    }

    private void init() {
        String ip = getLocalIpAddress();
        if (TextUtils.isEmpty(ip)) {
            textView.setText("获取不到IP，请连接网络");
        } else {
            String sb = "请在IE浏览器上输入网址访问FTP服务" + "\n" +
                    "ftp://" + ip + ":" + 2121 + "\n" +
                    "账号:" + "admin" + "\n" +
                    "密码:" + "123456";
            textView.setText(sb);
        }

        startService(new Intent(this, FtpService.class));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopService(new Intent(this, FtpService.class));
    }

    public String getLocalIpAddress() {
        String pattern = "192.168.*";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        String ip = inetAddress.getHostAddress();
                        boolean isMatch = Pattern.matches(pattern, ip);
                        if (isMatch) {
                            return ip;
                        }
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e(TAG, ex.toString());
        }
        return "";
    }
}